/**
 * @File AccountingCalendarDaoImpl.java


 * @author Agam Bhamra
 * @Version 1.0
 * @Date July 31, 2013
 * 
 * Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproducuce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */
package in.ac.dei.edrp.generalLedger.accountingCalendar;

import flex.messaging.FlexContext;



import flex.messaging.FlexSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

@Component
@Qualifier("AccountingCalendarDaoImpl")

public class AccountingCalendarDaoImpl extends SqlMapClientDaoSupport implements AccountingCalendarDao
{
	private static Logger logObj = Logger.getLogger(AccountingCalendarDaoImpl.class);
	
	public AccountingCalendarDaoImpl() {}
	@Autowired
	
	public AccountingCalendarDaoImpl (SqlMapClient sqlMapClient)
	{
		setSqlMapClient(sqlMapClient);
	}

	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public List<AccountingCalendarInfoBean> getEntries(AccountingCalendarInfoBean input) {
		
		List<AccountingCalendarInfoBean> entryList = null;
		try{
			entryList = getSqlMapClientTemplate().queryForList("accountingCalendar.selectAccountingCalendarDetails", input);
			
		}catch(Exception ex){
			
			logObj.info("Exception in getting all record method");
			logObj.error(ex);
		}
		return entryList;
	}
	
	public List<AccountingCalendarInfoBean> checkCalendar(String name)
	{
		List<AccountingCalendarInfoBean> checkCalendar = null;
		try{
			
			checkCalendar = getSqlMapClientTemplate().queryForList("accountingCalendar.checkCalendar", name);
				}catch(Exception ex){
			
			logObj.info("Exception in Adding new record method");
			logObj.error(ex);
			System.out.println(ex);
		}
		return checkCalendar;
	}
	
	public List<AccountingCalendarInfoBean> getMaxEntry()
	{
		List<AccountingCalendarInfoBean> getMaxEntry = null;
		try{
			
			getMaxEntry = getSqlMapClientTemplate().queryForList("accountingCalendar.getMaxEntry");
			}catch(Exception ex){
			
			logObj.info("Exception in getting Max Entry method");
			logObj.error(ex);
			System.out.println(ex);
		}
		return getMaxEntry;
	}
	
	public String deletePeriod(AccountingCalendarInfoBean input) {
		String status = "";
		try{		
			getSqlMapClientTemplate().delete("accountingCalendar.deletePeriod", input);
			
			status = "done";
		}catch(Exception ex){
			
			logObj.info("Exception in deletePeriod method");
			logObj.error(ex);
			status=ex.getClass().toString();
		}
		return status;
	}
	
	public String addcalendar(AccountingCalendarInfoBean input) {
		String status = "";
		try{		
			getSqlMapClientTemplate().insert("accountingCalendar.addcalendar", input);
			status = "done";
		}catch(Exception ex){
			
			logObj.info("Exception in deletePeriod method");
			logObj.error(ex.getClass());
			status = ex.getClass().toString();
		}
		return status;
	}
	
	
	public List<AccountingCalendarInfoBean> calendarList()
	{
		List<AccountingCalendarInfoBean> calendarList = null;
		try{
			
			calendarList = getSqlMapClientTemplate().queryForList("accountingCalendar.calendarList");
		}catch(Exception ex){
			
			logObj.info("Exception in Adding new record method");
			logObj.error(ex);
			System.out.println(ex);
			
		}
		return calendarList;
	}
	
	
	public String checkOverlapping(AccountingCalendarInfoBean input) {
		String status = "";
		try{		
			input = (AccountingCalendarInfoBean) getSqlMapClientTemplate().queryForObject("accountingCalendar.checkOverlapping", input);
			status = input.getName();
		}catch(Exception ex){
			
			logObj.info("Exception in deletePeriod method");
			logObj.error(ex.getClass());
			status = ex.getClass().toString();
		}
		return status;
	}
	
	@SuppressWarnings("unchecked")
	public String addEntries (final List<Map<String, String>> obj,final AccountingCalendarInfoBean input) {
		System.out.println("transaction addEntries started");
		String status="failure";
		status=(String)transactionTemplate.execute(new TransactionCallback(){
			
			Object savepoint;
			String result="failure";
			
		public String doInTransaction(TransactionStatus status){
			savepoint=status.createSavepoint();
			int i=0;
		try{
			if(obj.size()>0)
			{
				for(i=0;i<obj.size();i++)
				{
					System.out.println("addEntry Started");
					FlexSession session = FlexContext.getFlexSession();
			 		input.setUserId(session.getAttribute("userId").toString());
					input.setPrefix(obj.get(i).get("prefix"));
					input.setCalendarName(obj.get(i).get("calendarName"));
					System.out.println(input.getCalendarName());
					input.setType(obj.get(i).get("type"));
					input.setYear(obj.get(i).get("year"));
					input.setQuarter(obj.get(i).get("quarter"));
					input.setNumber(obj.get(i).get("number"));	
					input.setName(obj.get(i).get("name"));
					Date date= new Date(obj.get(i).get("fromDate"));
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					input.setFromDate((sdf.format(date)));
					date= new Date(obj.get(i).get("toDate"));
					input.setToDate((sdf.format(date)));
					input.setAdjustable(Boolean.parseBoolean(obj.get(i).get("adjustable")));
					int num;
					if(input.getAdjustable())
					{
						num=0;
					}
					else
					{
						AccountingCalendarInfoBean overlap = new AccountingCalendarInfoBean();
						overlap = (AccountingCalendarInfoBean) getSqlMapClientTemplate().queryForObject("accountingCalendar.checkOverlapping", input);
						String str = overlap.getName();
						num=Integer.parseInt(str);
					}
					if(num==0){
						getSqlMapClientTemplate().insert("accountingCalendar.addEntry", input);
						result="done";
						System.out.println(result);
						System.out.println("addEntry finished");
					}
					else{
						num=i+1;
						result=("Overlapping Periods at Row: "+num);
						System.out.println(result);
						status.rollbackToSavepoint(savepoint);
						break;
					}
				}
			}
		}
		catch (Exception e)
		{
			System.out.println(e);
			result=e.getClass().toString();
			if(result.equals("class org.springframework.dao.DuplicateKeyException"))
			{
				result="Duplicate Key Error! \n Row: "+(++i);
			}
			status.rollbackToSavepoint(savepoint);
		}
		return result;
		}
		});
		System.out.println("transaction addEntries completed");
		return status;
	}
	
	@SuppressWarnings("unchecked")
	public String editEntries (final List<Map<String, String>> obj,final AccountingCalendarInfoBean input) {
		System.out.println("transaction editEntries started");
		String status="Failure";
		status=(String)transactionTemplate.execute(new TransactionCallback(){
			
			Object savepoint;
			String result="Failure";
			
		public String doInTransaction(TransactionStatus status){
			savepoint=status.createSavepoint();
			
		int i=0;
		
		try{
			if(obj.size()>0)
			{
				for(i=0;i<obj.size();i++)
				{
					System.out.println("editEntries Started");
					FlexSession session = FlexContext.getFlexSession();
			 		input.setUserId(session.getAttribute("userId").toString());
					input.setPrefix(obj.get(i).get("prefix"));
					input.setCalendarName(obj.get(i).get("calendarName"));
					input.setType(obj.get(i).get("type"));
					input.setYear(obj.get(i).get("year"));
					input.setQuarter(obj.get(i).get("quarter"));
					input.setNumber(obj.get(i).get("number"));
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date date= new Date(obj.get(i).get("fromDate"));
					input.setFromDate((sdf.format(date)));
					date= new Date(obj.get(i).get("toDate"));
					input.setToDate((sdf.format(date)));
					input.setName(obj.get(i).get("name"));
					input.setAdjustable(Boolean.parseBoolean(obj.get(i).get("adjustable")));
					AccountingCalendarInfoBean overlap = new AccountingCalendarInfoBean();
					overlap = (AccountingCalendarInfoBean) getSqlMapClientTemplate().queryForObject("accountingCalendar.checkOverlapping", input);
					String str = overlap.getName();
					int num = Integer.parseInt(str);
					if(num==0){
						getSqlMapClientTemplate().update("accountingCalendar.editEntry", input);
						result="done";
						System.out.println("editEntries completed" + result);
					}
					else{
						num=new Integer(obj.get(i).get("rowIndex"));
						num++;
						result=("Overlapping Periods at Row: "+ num);
						status.rollbackToSavepoint(savepoint);
						break;
					}
				}
			}
		}
		catch (Exception e)
		{
			System.out.println(e);
			result = e.getClass().toString();
			status.rollbackToSavepoint(savepoint);
		}
		return result;
		}
		});
		System.out.println("transaction editEntries completed");
		return status;
	}
}
